package engine.services.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import engine.content.IContent;
import engine.services.IXsltService;


public class XsltService implements IXsltService {
	private XsltService() {
		
	}
	
	/* (non-Javadoc)
	 * @see engine.services.impl.IXsltService#transform(java.lang.String, engine.content.IContent)
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public String transform(String xsltFile, IContent content) throws Exception {
			
			File xslFile = new File(xsltFile);			
			if (! xslFile.exists()) {
				throw new FileNotFoundException("xslt file does not exist at: " + System.getProperty("user.dir") + File.separator + xsltFile);
			}
			StringReader sr = new StringReader(content.getContentAsString());
			StreamSource xmlSource = new StreamSource(sr);

			StreamSource xsltSource = new StreamSource(xslFile);

			StringWriter sw = new StringWriter();
			Result result = new StreamResult(sw);

			Transformer transformer = TransformerFactory.newInstance().newTransformer(xsltSource);
			transformer.transform(xmlSource, result);
			return sw.toString();			
	}

}
